package com.huawei.cloud.phone.management.application.user;

import com.huawei.cloud.phone.management.BaseTest;
import com.huawei.cloud.phone.management.Constants;
import com.huawei.cloud.phone.management.application.user.dto.LoginInfoDTO;
import com.huawei.cloud.phone.management.application.user.dto.UserDTO;
import com.huawei.cloud.phone.management.domain.cache.CacheResource;
import com.huawei.cloud.phone.management.domain.connection.Connection;
import com.huawei.cloud.phone.management.domain.connection.ConnectionGateway;
import com.huawei.cloud.phone.management.domain.phone.Phone;
import com.huawei.cloud.phone.management.domain.phone.PhoneGateway;
import com.huawei.cloud.phone.management.domain.phone.PhoneStatus;
import com.huawei.cloud.phone.management.domain.connection.ConnectionParam;
import com.huawei.cloud.phone.management.domain.user.User;
import com.huawei.cloud.phone.management.domain.user.UserGateway;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class UserServiceTest extends BaseTest {
    @Autowired
    private UserService userService;

    @MockBean
    private UserGateway userGateway;

    @MockBean
    private PhoneGateway phoneGateway;

    @MockBean
    private CacheResource<String> cacheResource;

    @MockBean
    private CacheResource<User> tokenCache;

    @Test
    public void register_success() {
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(Constants.USERNAME);
        userDTO.setPassword(Constants.PASSWORD);

        User user = mockUser(userDTO);
        User userFromDb = mockUserFromDb(user);
        Mockito.when(userGateway.saveUser(user)).thenReturn(Optional.of(userFromDb));
        Mockito.when(userGateway.getUser(Constants.USERNAME, Constants.PASSWORD_ENCRYPT)).thenReturn(Optional.of(userFromDb));
        Mockito.doNothing().when(cacheResource).cacheData(Mockito.any(), Mockito.any());
        Mockito.doNothing().when(tokenCache).cacheData(Mockito.any(), Mockito.any());

        Mockito.when(phoneGateway.addUserPhones(Mockito.any())).thenReturn(true);

        userService.register(userDTO);

        Mockito.verify(userGateway, Mockito.times(1)).saveUser(user);
    }

    private User mockUser(UserDTO userDTO) {
        User user = userDTO.toUser();
        user.handleSensitiveInfo();
        return user;
    }

    private User mockUserFromDb(User user) {
        User userFromDb = new User();
        userFromDb.setUsername(user.getUsername());
        userFromDb.setPassword(user.getPassword());
        userFromDb.setUserId(Constants.USER_ID);
        return userFromDb;
    }
}